<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FileCognize - 智能文档识别系统</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }

        .content {
            padding: 30px;
        }

        .upload-section {
            margin-bottom: 30px;
        }

        .upload-area {
            border: 3px dashed #ddd;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            transition: all 0.3s ease;
            background: #fafafa;
        }

        .upload-area.dragover {
            border-color: #4facfe;
            background: #f0f8ff;
        }

        .upload-buttons {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin: 20px 0;
            flex-wrap: wrap;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
        }

        .btn-success {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
            color: white;
        }

        .btn-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-warning {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
        }

        .btn-danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
            color: white;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-outline-primary {
            background: transparent;
            color: #4facfe;
            border: 2px solid #4facfe;
        }

        .btn-outline-secondary {
            background: transparent;
            color: #6c757d;
            border: 2px solid #6c757d;
        }

        .btn-sm {
            padding: 8px 16px;
            font-size: 14px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }

        .btn:disabled {
            background: #ccc !important;
            cursor: not-allowed;
            transform: none;
        }

        .progress {
            width: 100%;
            height: 20px;
            background: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
            margin: 20px 0;
            display: none;
        }

        .progress-bar {
            height: 100%;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            border-radius: 10px;
            transition: width 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }

        /* 进度条模态框样式 */
        .progress-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }

        .progress-modal-content {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.3);
            min-width: 400px;
            max-width: 500px;
            text-align: center;
        }

        .progress-modal h3 {
            margin-bottom: 20px;
            color: #333;
            font-size: 1.5em;
        }

        .progress-modal .progress {
            display: block;
            height: 25px;
            margin: 20px 0;
        }

        .progress-modal .progress-bar {
            font-size: 14px;
            font-weight: bold;
        }

        .progress-status {
            color: #666;
            font-size: 14px;
            margin-top: 10px;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #4facfe;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .results-container {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 25px;
            margin: 20px 0;
            border: 1px solid #e9ecef;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-control {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: #4facfe;
            box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
        }

        .form-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }

        .action-buttons {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 20px;
            flex-wrap: wrap;
        }

        .display-data {
            background: white;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }

        .field-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            margin: 10px 0;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #4facfe;
        }

        .field-label {
            font-weight: 600;
            color: #333;
            min-width: 150px;
        }

        .field-value {
            flex: 1;
            margin: 0 15px;
            padding: 8px 12px;
            background: white;
            border-radius: 4px;
            border: 1px solid #ddd;
        }

        .history-section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 25px;
            margin: 20px 0;
            border: 1px solid #e9ecef;
        }

        .history-controls {
            display: flex;
            gap: 15px;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .selected-count {
            margin-left: auto;
            font-weight: 600;
            color: #666;
        }

        .table-responsive {
            overflow-x: auto;
            margin: 20px 0;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .table th,
        .table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e9ecef;
        }

        .table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #333;
        }

        .table-striped tbody tr:nth-child(even) {
            background: #f8f9fa;
        }

        .table-hover tbody tr:hover {
            background: #e3f2fd;
        }

        .batch-actions {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 20px;
            flex-wrap: wrap;
        }

        .camera-section {
            margin-top: 20px;
            text-align: center;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        /* 全屏相机模式 */
        .camera-section.fullscreen {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            margin: 0;
            padding: 0;
            background: #000;
            border-radius: 0;
            box-shadow: none;
            z-index: 1000;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }

        .camera-section video {
            width: 100%;
            max-width: 500px;
            height: auto;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            background: #f0f0f0;
        }

        .camera-section.fullscreen video {
            width: 100vw;
            height: calc(100vh - 120px);
            max-width: none;
            border-radius: 0;
            box-shadow: none;
            object-fit: cover;
            background: #000;
        }

        .camera-controls {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            gap: 15px;
        }

        .camera-section.fullscreen .camera-controls {
            position: fixed;
            bottom: 30px;
            left: 0;
            right: 0;
            margin: 0;
            padding: 0 20px;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(10px);
            border-radius: 25px;
            max-width: 300px;
            margin: 0 auto;
        }

        .camera-section.fullscreen .camera-controls button {
            padding: 15px 25px;
            font-size: 16px;
            border-radius: 20px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            backdrop-filter: blur(5px);
        }

        .camera-section.fullscreen #cameraStatus {
            position: fixed;
            top: 30px;
            left: 0;
            right: 0;
            color: white;
            font-size: 16px;
            font-weight: bold;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8);
            z-index: 1001;
        }

        .camera-section.fullscreen #capturedImage {
            width: 100vw;
            height: calc(100vh - 120px);
            object-fit: contain;
            background: #000;
        }

        .photo-confirm-controls {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            gap: 15px;
        }

        .camera-section.fullscreen .photo-confirm-controls {
            position: fixed;
            bottom: 30px;
            left: 0;
            right: 0;
            margin: 0;
            padding: 0 20px;
            background: rgba(0, 0, 0, 0.6);
            backdrop-filter: blur(10px);
            border-radius: 25px;
            max-width: 400px;
            margin: 0 auto;
        }

        .camera-section.fullscreen .photo-confirm-controls button {
            padding: 12px 20px;
            font-size: 14px;
            border-radius: 18px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            backdrop-filter: blur(5px);
        }

        .alert {
            padding: 15px;
            margin: 20px 0;
            border-radius: 8px;
            border: 1px solid transparent;
        }

        .alert-success {
            color: #155724;
            background-color: #d4edda;
            border-color: #c3e6cb;
        }

        .alert-danger {
            color: #721c24;
            background-color: #f8d7da;
            border-color: #f5c6cb;
        }

        .alert-warning {
            color: #856404;
            background-color: #fff3cd;
            border-color: #ffeaa7;
        }

        .hidden {
            display: none !important;
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 10px;
            }
            
            .header {
                padding: 20px;
            }
            
            .header h1 {
                font-size: 2em;
            }
            
            .content {
                padding: 20px;
            }

            .field-item {
                flex-direction: column;
                align-items: stretch;
            }

            .field-label {
                min-width: auto;
                margin-bottom: 8px;
            }

            .field-value {
                margin: 0;
            }

            .history-controls {
                flex-direction: column;
                align-items: stretch;
            }

            .selected-count {
                margin-left: 0;
                text-align: center;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-search"></i> FileCognize</h1>
            <p>智能文档识别与数据提取系统</p>
        </div>
        
        <div class="content">
            <!-- 上传区域 -->
            <div class="upload-section">
                <div class="upload-area" id="uploadArea">
                    <h3><i class="fas fa-cloud-upload-alt"></i> 上传文档</h3>
                    <p>支持图片和PDF文件，点击选择文件或拖拽到此处</p>
                    
                    <div class="upload-buttons">
                        <button class="btn btn-primary" onclick="document.getElementById('fileInput').click()">
                            <i class="fas fa-folder-open"></i> 选择文件
                        </button>
                        <button class="btn btn-info" onclick="openCamera()">
                            <i class="fas fa-camera"></i> 拍照识别
                        </button>
                    </div>
                    
                    <input type="file" id="fileInput" accept="image/*,application/pdf" style="display: none;" />
                    
                    <!-- 相机界面 -->
                    <div class="camera-section" id="cameraSection" style="display: none;">
                        <div id="cameraStatus">正在启动相机...</div>
                        <video id="cameraVideo" autoplay playsinline muted></video>
                        <img id="capturedImage" style="display: none;" />
                        <div class="camera-controls">
                            <button class="btn btn-danger" onclick="closeCamera()">
                                <i class="fas fa-times"></i> 关闭相机
                            </button>
                            <button class="btn btn-success" id="captureBtn" onclick="capturePhoto()">
                                <i class="fas fa-camera"></i> 拍照
                            </button>
                        </div>
                        <!-- 拍照后的确认界面 -->
                        <div class="photo-confirm-controls" id="photoConfirmControls" style="display: none;">
                            <button class="btn btn-danger" onclick="closeCamera()">
                                <i class="fas fa-times"></i> 取消
                            </button>
                            <button class="btn btn-secondary" onclick="retakePhoto()">
                                <i class="fas fa-redo"></i> 重新拍照
                            </button>
                            <button class="btn btn-primary" onclick="confirmPhoto()">
                                <i class="fas fa-check"></i> 确认识别
                            </button>
                        </div>
                        <canvas id="captureCanvas" style="display: none;"></canvas>
                    </div>
                </div>
                
                <div class="progress" id="progress">
                    <div class="progress-bar" id="progressBar">0%</div>
                </div>
            </div>

            <!-- 识别结果区域 -->
            <div id="results" class="results-container" style="display: none;">
                <h3><i class="fas fa-eye"></i> 识别结果</h3>
                
                <!-- 可编辑的识别结果表单 -->
                <div class="edit-form" id="editForm" style="display: none;">
                    <div class="form-group">
                        <label for="editNumeroDocumento">Numero Documento:</label>
                        <input type="text" id="editNumeroDocumento" class="form-control">
                    </div>
                    <div class="form-group">
                        <label for="editQuantita">Quantita:</label>
                        <input type="text" id="editQuantita" class="form-control">
                    </div>
                    <div class="form-group">
                        <label for="editDescrizioneArticolo">Descrizione Articolo:</label>
                        <input type="text" id="editDescrizioneArticolo" class="form-control">
                    </div>
                    <div class="form-actions">
                        <button id="saveBtn" class="btn btn-success" onclick="saveEditedData()">
                            <i class="fas fa-save"></i> 保存
                        </button>
                        <button id="cancelBtn" class="btn btn-secondary" onclick="cancelEdit()">
                            <i class="fas fa-times"></i> 取消
                        </button>
                    </div>
                </div>
                
                <!-- 显示识别结果 -->
                <div id="displayData" class="display-data"></div>
                
                <!-- 操作按钮 -->
                <div class="action-buttons">
                    <button id="editBtn" class="btn btn-info" onclick="editData()" disabled>
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                    <button id="addToHistoryBtn" class="btn btn-success" onclick="addToHistory()" disabled>
                        <i class="fas fa-plus"></i> 添加到历史记录
                    </button>
                    <button class="btn btn-primary" onclick="resetForm()">
                        <i class="fas fa-redo"></i> 继续识别
                    </button>
                </div>
            </div>

            <!-- 历史记录区域 -->
            <div id="historySection" class="history-section" style="display: none;">
                <h3><i class="fas fa-history"></i> 历史记录</h3>
                <div class="history-controls">
                    <button id="selectAllBtn" class="btn btn-sm btn-outline-primary" onclick="selectAll()">
                        <i class="fas fa-check-square"></i> 全选
                    </button>
                    <button id="selectNoneBtn" class="btn btn-sm btn-outline-secondary" onclick="selectNone()">
                        <i class="fas fa-square"></i> 取消全选
                    </button>
                    <span class="selected-count">已选择: <span id="selectedCount">0</span> 条记录</span>
                </div>
                <div class="table-responsive">
                    <table id="historyTable" class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th width="50">
                                    <input type="checkbox" id="selectAllCheckbox" onchange="toggleSelectAll()">
                                </th>
                                <th width="150">导入时间</th>
                                <th width="120">Numero Documento</th>
                                <th width="100">Quantita</th>
                                <th>Descrizione Articolo</th>
                                <th width="100">操作</th>
                            </tr>
                        </thead>
                        <tbody id="historyTableBody">
                            <!-- 历史记录将在这里动态添加 -->
                        </tbody>
                    </table>
                </div>
                
                <!-- 批量操作按钮 -->
                <div class="batch-actions">
                    <button id="exportSelectedPdfBtn" class="btn btn-primary" onclick="exportSelectedPDF()" disabled>
                        <i class="fas fa-download"></i> 导出文件
                    </button>
                    <button id="printSelectedBtn" class="btn btn-secondary" onclick="printSelected()" disabled>
                        <i class="fas fa-print"></i> 打印选中记录
                    </button>
                    <button id="deleteSelectedBtn" class="btn btn-danger" onclick="deleteSelected()" disabled>
                        <i class="fas fa-trash"></i> 删除选中记录
                    </button>
                </div>
            </div>

            <!-- 消息提示区域 -->
            <div id="messageArea"></div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentSessionId = null;
        let currentData = null;
        let historyData = [];
        let cameraStream = null;

        // DOM 元素
        const fileInput = document.getElementById('fileInput');
        const uploadArea = document.getElementById('uploadArea');
        const progress = document.getElementById('progress');
        const progressBar = document.getElementById('progressBar');
        const results = document.getElementById('results');
        const displayData = document.getElementById('displayData');
        const editForm = document.getElementById('editForm');
        const historySection = document.getElementById('historySection');
        const historyTableBody = document.getElementById('historyTableBody');
        const messageArea = document.getElementById('messageArea');

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadHistoryData();
            setupEventListeners();
        });

        function setupEventListeners() {
            // 拖拽上传
            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.classList.add('dragover');
            });

            uploadArea.addEventListener('dragleave', () => {
                uploadArea.classList.remove('dragover');
            });

            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadArea.classList.remove('dragover');
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    handleFile(files[0]);
                }
            });

            // 文件选择
            fileInput.addEventListener('change', (e) => {
                if (e.target.files.length > 0) {
                    handleFile(e.target.files[0]);
                }
            });
        }

        // 文件处理
        async function handleFile(file) {
            if (!file.type.startsWith('image/') && file.type !== 'application/pdf') {
                showMessage('请选择图片文件或PDF文件！', 'danger');
                return;
            }

            const sessionId = generateSessionId();
            currentSessionId = sessionId;

            showProgress(true);
            updateProgress(10, '准备上传...');

            try {
                const formData = new FormData();
                formData.append('file', file);
                
                const endpoint = file.type === 'application/pdf' ? '/api/pdf-ocr-and-process' : '/api/ocr-and-process';

                updateProgress(30, '正在上传文件...');

                const response = await fetch(`${endpoint}?sessionId=${sessionId}`, {
                    method: 'POST',
                    body: formData
                });

                updateProgress(60, '正在识别文档...');

                const data = await response.json();

                updateProgress(100, '识别完成！');

                setTimeout(() => {
                    showProgress(false);
                    if (data.success) {
                        displayResult(data);
                    } else {
                        showMessage(data.message || '识别失败，请重试', 'danger');
                    }
                }, 1000);

            } catch (error) {
                showProgress(false);
                showMessage(`处理失败: ${error.message}`, 'danger');
            }
        }

        // 格式化识别数据
        function formatRecognizedData(extractedFields) {
            const formatted = { ...extractedFields };
            
            // 1. Quantita前面加上"N'"表示根数
            if (formatted['Quantita'] && formatted['Quantita'] !== '未识别') {
                const quantita = formatted['Quantita'].toString().trim();
                if (quantita && !quantita.startsWith('N\'')) {
                    formatted['Quantita'] = `N' ${quantita}`;
                    console.log(`📊 格式化Quantita: ${extractedFields['Quantita']} → ${formatted['Quantita']}`);
                }
            }
            
            // 2. Descrizione Articolo 特殊处理
            if (formatted['Descrizione Articolo'] && formatted['Descrizione Articolo'] !== '未识别') {
                let descrizione = formatted['Descrizione Articolo'].toString().trim();
                
                // 替换商品描述的四个类型中的 "A" 为 "DA"
                if (descrizione.includes('CERNIERE A SCORCIARE')) {
                    descrizione = descrizione.replace(/CERNIERE A SCORCIARE/g, 'CERNIERE DA SCORCIARE');
                    console.log(`📝 替换内容: CERNIERE A SCORCIARE → CERNIERE DA SCORCIARE`);
                }
                if (descrizione.includes('CERNIERE A MONTARE CURSORE')) {
                    descrizione = descrizione.replace(/CERNIERE A MONTARE CURSORE/g, 'CERNIERE DA MONTARE CURSORE');
                    console.log(`📝 替换内容: CERNIERE A MONTARE CURSORE → CERNIERE DA MONTARE CURSORE`);
                }
                if (descrizione.includes('CERNIERE A MONTARE TIRETTO')) {
                    descrizione = descrizione.replace(/CERNIERE A MONTARE TIRETTO/g, 'CERNIERE DA MONTARE TIRETTO');
                    console.log(`📝 替换内容: CERNIERE A MONTARE TIRETTO → CERNIERE DA MONTARE TIRETTO`);
                }
                
                // 后面加上"DDT"表示单据
                if (!descrizione.endsWith(' DDT')) {
                    descrizione = `${descrizione} DDT`;
                    console.log(`📝 添加DDT标识: ${formatted['Descrizione Articolo']} → ${descrizione}`);
                }
                
                formatted['Descrizione Articolo'] = descrizione;
            }
            
            return formatted;
        }

        // 显示识别结果
        function displayResult(data) {
            // 格式化识别数据
            const formattedFields = formatRecognizedData(data.extractedFields);
            
            currentData = {
                ...data,
                extractedFields: formattedFields, // 使用格式化后的数据
                timestamp: new Date().toISOString()
            };

            let html = '';
            const fields = ['Numero Documento', 'Quantita', 'Descrizione Articolo'];
            
            fields.forEach(field => {
                const value = formattedFields[field] || '未识别';
                html += `
                    <div class="field-item">
                        <div class="field-label">${field}:</div>
                        <div class="field-value">${value}</div>
                    </div>
                `;
            });

            displayData.innerHTML = html;
            results.style.display = 'block';
            
            // 启用按钮
            document.getElementById('editBtn').disabled = false;
            document.getElementById('addToHistoryBtn').disabled = false;

            showMessage('文档识别完成！数据已自动格式化。', 'success');
        }

        // 编辑数据
        function editData() {
            if (!currentData) return;

            // 填充编辑表单
            document.getElementById('editNumeroDocumento').value = currentData.extractedFields['Numero Documento'] || '';
            document.getElementById('editQuantita').value = currentData.extractedFields['Quantita'] || '';
            document.getElementById('editDescrizioneArticolo').value = currentData.extractedFields['Descrizione Articolo'] || '';

            // 显示编辑表单，隐藏显示区域
            editForm.style.display = 'block';
            displayData.style.display = 'none';
        }

        // 保存编辑的数据
        function saveEditedData() {
            const numeroDocumento = document.getElementById('editNumeroDocumento').value.trim();
            const quantita = document.getElementById('editQuantita').value.trim();
            const descrizioneArticolo = document.getElementById('editDescrizioneArticolo').value.trim();

            // 原始数据（编辑前的数据）
            const rawFields = {
                'Numero Documento': numeroDocumento,
                'Quantita': quantita,
                'Descrizione Articolo': descrizioneArticolo
            };

            // 应用格式化规则
            const formattedFields = formatRecognizedData(rawFields);

            // 更新当前数据
            currentData.extractedFields = formattedFields;

            // 重新显示结果
            displayResult(currentData);
            cancelEdit();
            
            showMessage('数据已保存并格式化！', 'success');
        }

        // 取消编辑
        function cancelEdit() {
            editForm.style.display = 'none';
            displayData.style.display = 'block';
        }

        // 添加到历史记录
        function addToHistory() {
            if (!currentData) return;

            // 检查是否已存在相同记录
            const duplicateRecord = historyData.find(item => 
                item.extractedFields['Numero Documento'] === currentData.extractedFields['Numero Documento'] &&
                item.extractedFields['Quantita'] === currentData.extractedFields['Quantita'] &&
                item.extractedFields['Descrizione Articolo'] === currentData.extractedFields['Descrizione Articolo']
            );

            if (duplicateRecord) {
                // 显示重复记录确认对话框
                showDuplicateConfirmDialog(duplicateRecord);
                return;
            }

            // 添加到历史记录
            addRecordToHistory();
        }

        // 显示重复记录确认对话框
        function showDuplicateConfirmDialog(duplicateRecord) {
            const modal = document.createElement('div');
            modal.className = 'duplicate-modal';
            modal.innerHTML = `
                <div class="duplicate-modal-content">
                    <div class="duplicate-modal-header">
                        <h3><i class="fas fa-exclamation-triangle text-warning"></i> 发现重复记录</h3>
                    </div>
                    <div class="duplicate-modal-body">
                        <p><strong>检测到相似的记录已存在：</strong></p>
                        <div class="duplicate-record-info">
                            <div class="record-item">
                                <strong>现有记录：</strong>
                                <ul>
                                    <li><strong>添加时间：</strong> ${formatDateTime(duplicateRecord.timestamp)}</li>
                                    <li><strong>文档编号：</strong> ${duplicateRecord.extractedFields['Numero Documento'] || '-'}</li>
                                    <li><strong>数量：</strong> ${duplicateRecord.extractedFields['Quantita'] || '-'}</li>
                                    <li><strong>描述：</strong> ${duplicateRecord.extractedFields['Descrizione Articolo'] || '-'}</li>
                                </ul>
                            </div>
                            <div class="record-item">
                                <strong>新记录：</strong>
                                <ul>
                                    <li><strong>文件名：</strong> ${currentData.filename || '未知文件'}</li>
                                    <li><strong>文档编号：</strong> ${currentData.extractedFields['Numero Documento'] || '-'}</li>
                                    <li><strong>数量：</strong> ${currentData.extractedFields['Quantita'] || '-'}</li>
                                    <li><strong>描述：</strong> ${currentData.extractedFields['Descrizione Articolo'] || '-'}</li>
                                </ul>
                            </div>
                        </div>
                        <p class="duplicate-question"><strong>是否仍要添加这条新记录？</strong></p>
                    </div>
                    <div class="duplicate-modal-footer">
                        <button class="btn btn-secondary" onclick="closeDuplicateModal()">
                            <i class="fas fa-times"></i> 取消
                        </button>
                        <button class="btn btn-primary" onclick="confirmAddDuplicate()">
                            <i class="fas fa-plus"></i> 仍要添加
                        </button>
                    </div>
                </div>
            `;

            document.body.appendChild(modal);
            
            // 添加样式
            if (!document.getElementById('duplicateModalStyles')) {
                const style = document.createElement('style');
                style.id = 'duplicateModalStyles';
                style.textContent = `
                    .duplicate-modal {
                        position: fixed;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        background-color: rgba(0, 0, 0, 0.5);
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        z-index: 1000;
                    }
                    
                    .duplicate-modal-content {
                        background: white;
                        border-radius: 8px;
                        max-width: 600px;
                        width: 90%;
                        max-height: 80vh;
                        overflow-y: auto;
                        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
                    }
                    
                    .duplicate-modal-header {
                        padding: 20px 20px 10px;
                        border-bottom: 1px solid #dee2e6;
                    }
                    
                    .duplicate-modal-header h3 {
                        margin: 0;
                        color: #495057;
                    }
                    
                    .duplicate-modal-body {
                        padding: 20px;
                    }
                    
                    .duplicate-record-info {
                        background: #f8f9fa;
                        border-radius: 6px;
                        padding: 15px;
                        margin: 15px 0;
                    }
                    
                    .record-item {
                        margin-bottom: 15px;
                    }
                    
                    .record-item:last-child {
                        margin-bottom: 0;
                    }
                    
                    .record-item ul {
                        margin: 8px 0 0 20px;
                        padding: 0;
                    }
                    
                    .record-item li {
                        margin: 5px 0;
                        color: #6c757d;
                    }
                    
                    .duplicate-question {
                        margin-top: 20px;
                        color: #495057;
                        font-size: 16px;
                    }
                    
                    .duplicate-modal-footer {
                        padding: 15px 20px 20px;
                        text-align: right;
                        border-top: 1px solid #dee2e6;
                    }
                    
                    .duplicate-modal-footer .btn {
                        margin-left: 10px;
                    }
                    
                    .text-warning {
                        color: #ffc107 !important;
                    }
                `;
                document.head.appendChild(style);
            }
        }

        // 关闭重复记录对话框
        function closeDuplicateModal() {
            const modal = document.querySelector('.duplicate-modal');
            if (modal) {
                document.body.removeChild(modal);
            }
        }

        // 确认添加重复记录
        function confirmAddDuplicate() {
            closeDuplicateModal();
            addRecordToHistory();
            showMessage('记录已添加到历史记录！（包含重复记录）', 'success');
        }

        // 实际添加记录到历史的函数
        async function addRecordToHistory() {
            const historyItem = {
                id: generateId(),
                timestamp: new Date().toISOString(),
                extractedFields: { ...currentData.extractedFields },
                filename: currentData.filename || '未知文件'
            };

            historyData.push(historyItem);
            saveHistoryData(); // 保存到本地存储
            
            // 同时保存到服务器
            const serverSaved = await saveHistoryToServer(historyItem);
            
            renderHistoryTable();
            
            // 显示历史记录区域
            historySection.style.display = 'block';
            
            if (!document.querySelector('.duplicate-modal')) {
                if (serverSaved) {
                    showMessage('记录已添加到历史记录并同步到服务器！', 'success');
                } else {
                    showMessage('记录已添加到历史记录（仅本地保存）', 'warning');
                }
            }
        }

        // 渲染历史记录表格
        function renderHistoryTable() {
            if (historyData.length === 0) {
                historyTableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #666;">暂无历史记录</td></tr>';
                return;
            }

            // 按时间倒序排列（最新的在前面）
            const sortedData = [...historyData].sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));

            historyTableBody.innerHTML = sortedData.map(item => `
                <tr>
                    <td>
                        <input type="checkbox" class="record-checkbox" value="${item.id}" onchange="updateSelectedCount()">
                    </td>
                    <td>${formatDateTime(item.timestamp)}</td>
                    <td>${item.extractedFields['Numero Documento'] || '-'}</td>
                    <td>${item.extractedFields['Quantita'] || '-'}</td>
                    <td>${item.extractedFields['Descrizione Articolo'] || '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-danger" onclick="deleteRecord('${item.id}')">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');

            updateSelectedCount();
        }

        // 选择/取消选择所有记录
        function toggleSelectAll() {
            const selectAllCheckbox = document.getElementById('selectAllCheckbox');
            const checkboxes = document.querySelectorAll('.record-checkbox');
            
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
            });
            
            updateSelectedCount();
        }

        function selectAll() {
            document.getElementById('selectAllCheckbox').checked = true;
            toggleSelectAll();
        }

        function selectNone() {
            document.getElementById('selectAllCheckbox').checked = false;
            toggleSelectAll();
        }

        // 更新选中计数
        function updateSelectedCount() {
            const checkboxes = document.querySelectorAll('.record-checkbox:checked');
            const count = checkboxes.length;
            
            document.getElementById('selectedCount').textContent = count;
            
            // 更新批量操作按钮状态
            const hasSelection = count > 0;
            document.getElementById('exportSelectedPdfBtn').disabled = !hasSelection; // 导出文件按钮
            document.getElementById('printSelectedBtn').disabled = !hasSelection;
            document.getElementById('deleteSelectedBtn').disabled = !hasSelection;
        }

        // 设备检测函数
        function detectDevice() {
            const userAgent = navigator.userAgent.toLowerCase();
            const isMobile = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent);
            const isTablet = /ipad|android(?!.*mobile)/i.test(userAgent);
            
            return {
                isMobile: isMobile && !isTablet,
                isTablet: isTablet,
                isDesktop: !isMobile && !isTablet,
                userAgent: userAgent
            };
        }

        // 导出选中记录 - 支持跨设备格式一致性
        async function exportSelected() {
            const selectedIds = getSelectedRecordIds();
            if (selectedIds.length === 0) {
                showMessage('请选择要导出的记录！', 'warning');
                return;
            }

            try {
                const selectedRecords = historyData.filter(item => selectedIds.includes(item.id));
                const device = detectDevice();
                
                console.log('📱 设备信息:', device);
                
                // 创建临时会话ID
                const tempSessionId = generateSessionId();
                
                // 根据设备类型选择导出方式
                let exportEndpoint = '/api/export-selected';
                let exportMode = 'standard';
                
                if (device.isMobile) {
                    exportMode = 'mobile-optimized';
                    console.log('📱 使用移动端优化导出模式');
                    showMessage('检测到移动设备，使用优化导出模式...', 'info');
                } else if (device.isTablet) {
                    exportMode = 'tablet-optimized';
                    console.log('📱 使用平板优化导出模式');
                } else {
                    exportMode = 'desktop-standard';
                    console.log('💻 使用桌面标准导出模式');
                }
                
                // 发送选中的记录到后端，包含设备信息
                const response = await fetch(exportEndpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        sessionId: tempSessionId,
                        records: selectedRecords,
                        deviceInfo: {
                            type: device.isMobile ? 'mobile' : device.isTablet ? 'tablet' : 'desktop',
                            userAgent: device.userAgent,
                            exportMode: exportMode
                        }
                    })
                });

                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    
                    // 根据设备类型调整文件名
                    const timestamp = formatDateTime(new Date().toISOString()).replace(/[:\s]/g, '-');
                    const deviceSuffix = device.isMobile ? '_Mobile' : device.isTablet ? '_Tablet' : '';
                    a.download = `FileCognize_Selected${deviceSuffix}_${timestamp}.xlsx`;
                    
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                    
                    let successMessage = `✅ 成功导出 ${selectedIds.length} 条记录为Excel格式！`;
                    if (device.isMobile) {
                        successMessage += ' (移动端优化版本)';
                    } else if (device.isTablet) {
                        successMessage += ' (平板优化版本)';
                    }
                    showMessage(successMessage, 'success');
                    
                    // 为用户提供Excel格式说明
                    setTimeout(() => {
                        showMessage('📊 Excel格式优势：可编辑数据，支持公式计算和进一步处理', 'info');
                    }, 2000);
                    
                    // 为移动端用户提供额外说明
                    if (device.isMobile || device.isTablet) {
                        setTimeout(() => {
                            showMessage('🎨 移动端专用：完全保持原始Excel格式，包含所有表头信息', 'info');
                        }, 2000);
                        
                        setTimeout(() => {
                            showMessage('📋 表头完整：公司信息、文档标题、合并单元格全部保持', 'success');
                        }, 4000);
                        
                        setTimeout(() => {
                            showMessage('📱 可直接打开Excel查看完整文档，格式与原模板100%一致', 'info');
                        }, 6000);
                    }
                } else {
                    throw new Error('导出失败');
                }
            } catch (error) {
                console.error('导出失败:', error);
                showMessage(`导出失败: ${error.message}`, 'danger');
            }
        }

        // 导出选中记录为PDF - 避免跨平台差异
        async function exportSelectedPDF() {
            const selectedIds = getSelectedRecordIds();
            if (selectedIds.length === 0) {
                showMessage('请选择要导出的记录！', 'warning');
                return;
            }

            try {
                const selectedRecords = historyData.filter(item => selectedIds.includes(item.id));
                const device = detectDevice();
                
                console.log('📄 PDF导出设备信息:', device);
                
                // 创建临时会话ID
                const tempSessionId = generateSessionId();
                
                // 显示进度条模态框
                showProgressModal('正在导出文件...', '正在准备导出数据...');
                updateProgressModal(10, '正在准备导出数据...');
                
                // 发送选中的记录到后端生成PDF
                updateProgressModal(30, '正在生成Excel文件...');
                const response = await fetch('/api/export-selected-pdf', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        sessionId: tempSessionId,
                        records: selectedRecords,
                        deviceInfo: {
                            type: device.isMobile ? 'mobile' : device.isTablet ? 'tablet' : 'desktop',
                            userAgent: device.userAgent,
                            exportMode: 'pdf-export'
                        }
                    })
                });

                if (response.ok) {
                    updateProgressModal(70, '正在转换为PDF格式...');
                    const blob = await response.blob();
                    updateProgressModal(90, '正在准备下载...');
                    
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    
                    // 根据设备类型调整文件名
                    const timestamp = formatDateTime(new Date().toISOString()).replace(/[:\s]/g, '-');
                    const deviceSuffix = device.isMobile ? '_Mobile' : device.isTablet ? '_Tablet' : '';
                    a.download = `FileCognize_Selected${deviceSuffix}_${timestamp}.pdf`;
                    
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                    
                    updateProgressModal(100, '导出完成！');
                    
                    // 延迟隐藏进度条，让用户看到完成状态
                    setTimeout(() => {
                        hideProgressModal();
                    }, 1000);
                    
                    let successMessage = `✅ 成功导出 ${selectedIds.length} 条记录为PDF！`;
                    showMessage(successMessage, 'success');
                    
                    // 为用户提供PDF优势说明
                    setTimeout(() => {
                        showMessage('📄 PDF格式优势：跨平台完全一致，无论在Windows、Mac还是手机上都显示相同', 'info');
                    }, 2000);
                    
                    setTimeout(() => {
                        showMessage('🖨️ PDF文件可直接打印或分享，格式永不变形，适合正式文档存档', 'success');
                    }, 4000);
                    
                    setTimeout(() => {
                        showMessage('💡 提示：如需编辑数据，可使用"导出Excel"按钮获取可编辑版本', 'info');
                    }, 6000);
                } else {
                    throw new Error('PDF导出失败');
                }
            } catch (error) {
                console.error('PDF导出失败:', error);
                hideProgressModal();
                showMessage(`PDF导出失败: ${error.message}`, 'danger');
            }
        }

        // 打印选中记录
        async function printSelected() {
            const selectedIds = getSelectedRecordIds();
            if (selectedIds.length === 0) {
                showMessage('请选择要打印的记录！', 'warning');
                return;
            }

            try {
                const selectedRecords = historyData.filter(item => selectedIds.includes(item.id));
                
                // 显示进度条模态框
                showProgressModal('正在准备打印...', '正在准备打印数据...');
                updateProgressModal(10, '正在准备打印数据...');
                
                // 创建临时会话ID
                const tempSessionId = generateSessionId();
                
                // 发送选中的记录到后端生成打印页面
                updateProgressModal(30, '正在生成打印文件...');
                const response = await fetch('/api/print-selected', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        sessionId: tempSessionId,
                        records: selectedRecords
                    })
                });

                if (response.ok) {
                    updateProgressModal(70, '正在转换为PDF格式...');
                    // 获取PDF文件的blob数据
                    const pdfBlob = await response.blob();
                    
                    updateProgressModal(90, '正在准备打印窗口...');
                    // 创建PDF文件的URL
                    const pdfUrl = URL.createObjectURL(pdfBlob);
                    
                    // 在新窗口中打开PDF文件
                    const printWindow = window.open(pdfUrl, '_blank');
                    
                    updateProgressModal(100, '打印准备完成！');
                    
                    // 延迟隐藏进度条
                    setTimeout(() => {
                        hideProgressModal();
                    }, 1000);
                    
                    // 清理URL对象（延迟清理，确保PDF已加载）
                    setTimeout(() => {
                        URL.revokeObjectURL(pdfUrl);
                    }, 10000);
                    
                    showMessage(`成功准备打印 ${selectedIds.length} 条记录！PDF文件已在新窗口中打开`, 'success');
                } else {
                    throw new Error('打印准备失败');
                }
            } catch (error) {
                hideProgressModal();
                showMessage(`打印失败: ${error.message}`, 'danger');
            }
        }

        // 删除选中记录
        async function deleteSelected() {
            const selectedIds = getSelectedRecordIds();
            if (selectedIds.length === 0) {
                showMessage('请选择要删除的记录！', 'warning');
                return;
            }

            if (confirm(`确定要删除选中的 ${selectedIds.length} 条记录吗？此操作不可撤销。`)) {
                // 同时从服务器删除
                for (const id of selectedIds) {
                    await deleteHistoryFromServer(id);
                }
                
                historyData = historyData.filter(item => !selectedIds.includes(item.id));
                saveHistoryData();
                renderHistoryTable();
                
                showMessage(`成功删除 ${selectedIds.length} 条记录！`, 'success');
            }
        }

        // 删除单条记录
        async function deleteRecord(id) {
            if (confirm('确定要删除这条记录吗？此操作不可撤销。')) {
                // 同时从服务器删除
                await deleteHistoryFromServer(id);
                
                historyData = historyData.filter(item => item.id !== id);
                saveHistoryData();
                renderHistoryTable();
                
                showMessage('记录已删除！', 'success');
            }
        }

        // 获取选中记录的ID
        function getSelectedRecordIds() {
            const checkboxes = document.querySelectorAll('.record-checkbox:checked');
            return Array.from(checkboxes).map(checkbox => checkbox.value);
        }

        // 相机功能
        async function openCamera() {
            try {
                // 请求高质量视频流，提升识别准确率
                const constraints = {
                    video: {
                        facingMode: 'environment', // 优先使用后置摄像头
                        width: { ideal: 1920, min: 1280 }, // 高分辨率
                        height: { ideal: 1080, min: 720 },
                        aspectRatio: { ideal: 16/9 }
                    }
                };
                
                cameraStream = await navigator.mediaDevices.getUserMedia(constraints);
                
                const video = document.getElementById('cameraVideo');
                const cameraSection = document.getElementById('cameraSection');
                
                video.srcObject = cameraStream;
                
                // 启用全屏模式
                cameraSection.classList.add('fullscreen');
                cameraSection.style.display = 'block';
                
                // 阻止页面滚动
                document.body.style.overflow = 'hidden';
                
                document.getElementById('cameraStatus').textContent = '相机已就绪，对准文档点击拍照按钮';
                
                // 添加ESC键退出功能
                document.addEventListener('keydown', handleEscapeKey);
                
            } catch (error) {
                console.error('相机启动失败:', error);
                showMessage('无法访问相机，请检查权限设置或尝试使用其他浏览器', 'danger');
            }
        }

        function closeCamera() {
            if (cameraStream) {
                cameraStream.getTracks().forEach(track => track.stop());
                cameraStream = null;
            }
            
            // 清理预览图片资源
            const capturedImage = document.getElementById('capturedImage');
            if (capturedImage.src) {
                URL.revokeObjectURL(capturedImage.src);
                capturedImage.src = '';
            }
            
            const cameraSection = document.getElementById('cameraSection');
            cameraSection.classList.remove('fullscreen');
            cameraSection.style.display = 'none';
            
            // 重置界面状态
            document.getElementById('cameraVideo').style.display = 'block';
            document.getElementById('capturedImage').style.display = 'none';
            document.querySelector('.camera-controls').style.display = 'flex';
            document.getElementById('photoConfirmControls').style.display = 'none';
            
            // 恢复页面滚动
            document.body.style.overflow = 'auto';
            
            // 移除ESC键监听
            document.removeEventListener('keydown', handleEscapeKey);
            
            // 清理数据
            capturedPhotoBlob = null;
        }

        function handleEscapeKey(event) {
            if (event.key === 'Escape') {
                closeCamera();
            }
        }

        let capturedPhotoBlob = null; // 存储拍摄的照片

        function capturePhoto() {
            const video = document.getElementById('cameraVideo');
            const canvas = document.getElementById('captureCanvas');
            const context = canvas.getContext('2d');
            
            // 使用更高的分辨率进行拍照，提升OCR识别率
            const scale = 2; // 2倍超级采样
            canvas.width = video.videoWidth * scale;
            canvas.height = video.videoHeight * scale;
            
            // 设置高质量绘制
            context.imageSmoothingEnabled = true;
            context.imageSmoothingQuality = 'high';
            
            // 缩放画布以获得更高质量
            context.scale(scale, scale);
            context.drawImage(video, 0, 0);
            
            // 图像预处理以提升OCR识别率
            try {
                const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
                const processedImageData = enhanceImageForOCR(imageData);
                context.putImageData(processedImageData, 0, 0);
                console.log('✅ 图像预处理完成');
            } catch (error) {
                console.warn('⚠️ 图像预处理失败，使用原始图像:', error.message);
            }
            
            // 生成照片预览
            canvas.toBlob(blob => {
                console.log('拍照完成，图片大小:', (blob.size / 1024 / 1024).toFixed(2), 'MB');
                
                // 存储照片blob供后续使用
                capturedPhotoBlob = blob;
                
                // 显示照片预览
                const capturedImage = document.getElementById('capturedImage');
                const imageUrl = URL.createObjectURL(blob);
                capturedImage.src = imageUrl;
                
                // 切换到预览模式
                document.getElementById('cameraVideo').style.display = 'none';
                document.getElementById('capturedImage').style.display = 'block';
                
                // 评估图像质量并提供建议
                evaluatePhotoQuality(blob).then(quality => {
                    if (quality.score >= 80) {
                        document.getElementById('cameraStatus').textContent = '✅ 照片质量良好，文字清晰可见';
                        document.getElementById('cameraStatus').style.color = '#28a745';
                    } else if (quality.score >= 60) {
                        document.getElementById('cameraStatus').textContent = '⚠️ 照片质量一般，建议重新拍照';
                        document.getElementById('cameraStatus').style.color = '#ffc107';
                    } else {
                        document.getElementById('cameraStatus').textContent = '❌ 照片质量较差，建议重新拍照';
                        document.getElementById('cameraStatus').style.color = '#dc3545';
                    }
                }).catch(() => {
                    document.getElementById('cameraStatus').textContent = '请确认照片质量，文字是否清晰可见';
                });
                
                // 切换控制按钮
                document.querySelector('.camera-controls').style.display = 'none';
                document.getElementById('photoConfirmControls').style.display = 'flex';
                
            }, 'image/jpeg', 0.95); // 使用95%质量而不是80%
        }

        async function confirmPhoto() {
            if (!capturedPhotoBlob) {
                showMessage('未找到拍照数据，请重新拍照', 'danger');
                return;
            }
            
            // 创建高质量的文件对象
            const file = new File([capturedPhotoBlob], 'camera-capture.jpg', { 
                type: 'image/jpeg',
                lastModified: Date.now()
            });
            
            console.log('📸 拍照文件信息:', {
                name: file.name,
                size: (file.size / 1024 / 1024).toFixed(2) + ' MB',
                type: file.type
            });
            
            closeCamera();
            
            // 使用增强的文件处理流程
            await handleCameraFile(file);
        }

        // 专门为拍照文件优化的处理函数
        async function handleCameraFile(file) {
            if (!file.type.startsWith('image/')) {
                showMessage('拍照文件类型错误，请重新拍照', 'danger');
                return;
            }

            const sessionId = generateSessionId();
            currentSessionId = sessionId;

            showProgress(true);
            updateProgress(5, '正在准备拍照文件...');

            try {
                const formData = new FormData();
                formData.append('file', file);
                
                // 添加额外的拍照标识，帮助后端优化处理
                formData.append('source', 'camera');
                formData.append('enhanced', 'true'); // 标识已经过前端图像增强
                
                updateProgress(15, '正在上传拍照文件...');

                const response = await fetch(`/api/ocr-and-process?sessionId=${sessionId}`, {
                    method: 'POST',
                    body: formData
                });

                updateProgress(40, '正在进行OCR识别...');

                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`服务器错误: ${response.status} - ${errorText}`);
                }

                const data = await response.json();

                updateProgress(85, '正在处理识别结果...');

                // 添加延迟以显示进度
                await new Promise(resolve => setTimeout(resolve, 500));

                updateProgress(100, '识别完成！');

                setTimeout(() => {
                    showProgress(false);
                    if (data.success) {
                        console.log('📊 拍照识别成功:', data);
                        showMessage('拍照识别成功！', 'success');
                        displayResult(data);
                    } else {
                        console.error('❌ 拍照识别失败:', data);
                        showMessage(`拍照识别失败: ${data.error || data.message || '未知错误'}`, 'danger');
                        
                        // 提供重新拍照的建议
                        setTimeout(() => {
                            showMessage('建议重新拍照，确保文档清晰且光线充足', 'warning');
                        }, 3000);
                    }
                }, 1000);

            } catch (error) {
                console.error('❌ 拍照处理失败:', error);
                showProgress(false);
                
                let errorMessage = '拍照识别失败';
                if (error.message.includes('timeout')) {
                    errorMessage = '识别超时，请检查网络连接后重试';
                } else if (error.message.includes('网络')) {
                    errorMessage = '网络错误，请检查连接后重试';
                } else if (error.message.includes('服务器')) {
                    errorMessage = '服务器错误，请稍后重试';
                } else {
                    errorMessage = `处理失败: ${error.message}`;
                }
                
                showMessage(errorMessage, 'danger');
                
                // 提供操作建议
                setTimeout(() => {
                    showMessage('请尝试重新拍照或使用文件上传功能', 'info');
                }, 3000);
            }
        }

        function retakePhoto() {
            // 清理预览图片
            const capturedImage = document.getElementById('capturedImage');
            if (capturedImage.src) {
                URL.revokeObjectURL(capturedImage.src);
            }
            
            // 重置界面
            document.getElementById('cameraVideo').style.display = 'block';
            document.getElementById('capturedImage').style.display = 'none';
            document.getElementById('cameraStatus').textContent = '相机已就绪，对准文档点击拍照按钮';
            
            // 切换控制按钮
            document.querySelector('.camera-controls').style.display = 'flex';
            document.getElementById('photoConfirmControls').style.display = 'none';
            
            // 清理数据
            capturedPhotoBlob = null;
        }

        // 图像质量评估函数
        async function evaluatePhotoQuality(blob) {
            return new Promise((resolve, reject) => {
                try {
                    const img = new Image();
                    img.onload = function() {
                        const canvas = document.createElement('canvas');
                        const ctx = canvas.getContext('2d');
                        
                        canvas.width = img.width;
                        canvas.height = img.height;
                        ctx.drawImage(img, 0, 0);
                        
                        const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                        const data = imageData.data;
                        
                        let totalVariance = 0;
                        let brightPixels = 0;
                        let darkPixels = 0;
                        let totalBrightness = 0;
                        
                        // 计算图像清晰度和对比度
                        for (let i = 0; i < data.length; i += 4) {
                            const r = data[i];
                            const g = data[i + 1];
                            const b = data[i + 2];
                            
                            const gray = 0.299 * r + 0.587 * g + 0.114 * b;
                            totalBrightness += gray;
                            
                            if (gray > 200) brightPixels++;
                            if (gray < 50) darkPixels++;
                            
                            // 计算局部方差（清晰度指标）
                            if (i > 0 && i < data.length - 4) {
                                const prevGray = 0.299 * data[i-4] + 0.587 * data[i-3] + 0.114 * data[i-2];
                                totalVariance += Math.abs(gray - prevGray);
                            }
                        }
                        
                        const pixelCount = data.length / 4;
                        const avgBrightness = totalBrightness / pixelCount;
                        const avgVariance = totalVariance / pixelCount;
                        const contrastRatio = (brightPixels + darkPixels) / pixelCount;
                        
                        // 计算质量分数
                        let score = 50; // 基础分数
                        
                        // 清晰度评分（0-30分）
                        if (avgVariance > 15) score += 30;
                        else if (avgVariance > 10) score += 20;
                        else if (avgVariance > 5) score += 10;
                        
                        // 亮度评分（0-20分）
                        if (avgBrightness >= 80 && avgBrightness <= 180) score += 20;
                        else if (avgBrightness >= 60 && avgBrightness <= 200) score += 10;
                        
                        // 对比度评分（0-20分）
                        if (contrastRatio >= 0.3 && contrastRatio <= 0.7) score += 20;
                        else if (contrastRatio >= 0.2 && contrastRatio <= 0.8) score += 10;
                        
                        // 图像尺寸评分（0-10分）
                        if (canvas.width >= 800 && canvas.height >= 600) score += 10;
                        else if (canvas.width >= 640 && canvas.height >= 480) score += 5;
                        
                        resolve({
                            score: Math.min(100, Math.max(0, score)),
                            brightness: avgBrightness,
                            sharpness: avgVariance,
                            contrast: contrastRatio,
                            dimensions: { width: canvas.width, height: canvas.height }
                        });
                    };
                    
                    img.onerror = () => reject(new Error('图像加载失败'));
                    img.src = URL.createObjectURL(blob);
                } catch (error) {
                    reject(error);
                }
            });
        }

        // 图像增强函数，提升OCR识别率
        function enhanceImageForOCR(imageData) {
            const data = imageData.data;
            const width = imageData.width;
            const height = imageData.height;
            
            // 创建新的图像数据
            const enhancedData = new Uint8ClampedArray(data);
            
            // 1. 提升对比度和亮度
            for (let i = 0; i < data.length; i += 4) {
                const r = data[i];
                const g = data[i + 1];
                const b = data[i + 2];
                
                // 计算灰度值
                const gray = 0.299 * r + 0.587 * g + 0.114 * b;
                
                // 应用对比度增强
                const contrast = 1.3; // 增强对比度
                const brightness = 10;  // 轻微提升亮度
                
                let newR = contrast * (r - 128) + 128 + brightness;
                let newG = contrast * (g - 128) + 128 + brightness;
                let newB = contrast * (b - 128) + 128 + brightness;
                
                // 如果像素偏向灰色，增强黑白对比
                if (Math.abs(r - g) < 30 && Math.abs(g - b) < 30 && Math.abs(r - b) < 30) {
                    if (gray < 140) {
                        // 使暗部更暗
                        newR = Math.max(0, newR - 20);
                        newG = Math.max(0, newG - 20);
                        newB = Math.max(0, newB - 20);
                    } else {
                        // 使亮部更亮
                        newR = Math.min(255, newR + 15);
                        newG = Math.min(255, newG + 15);
                        newB = Math.min(255, newB + 15);
                    }
                }
                
                // 限制像素值范围
                enhancedData[i] = Math.max(0, Math.min(255, newR));
                enhancedData[i + 1] = Math.max(0, Math.min(255, newG));
                enhancedData[i + 2] = Math.max(0, Math.min(255, newB));
                enhancedData[i + 3] = data[i + 3]; // 保持alpha通道
            }
            
            return new ImageData(enhancedData, width, height);
        }

        // 重置表单
        function resetForm() {
            currentData = null;
            currentSessionId = null;
            
            results.style.display = 'none';
            editForm.style.display = 'none';
            displayData.style.display = 'block';
            
            document.getElementById('editBtn').disabled = true;
            document.getElementById('addToHistoryBtn').disabled = true;
            
            fileInput.value = '';
            
            // 如果有历史记录，显示历史记录区域
            if (historyData.length > 0) {
                historySection.style.display = 'block';
            }
        }

        // 工具函数
        function generateSessionId() {
            return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        }

        function generateId() {
            return 'record_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        }

        function formatDateTime(isoString) {
            const date = new Date(isoString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        }

        function showProgress(show) {
            progress.style.display = show ? 'block' : 'none';
            if (!show) {
                updateProgress(0, '');
            }
        }

        function updateProgress(percent, text) {
            progressBar.style.width = percent + '%';
            progressBar.textContent = text || `${percent}%`;
        }

        function showMessage(message, type = 'info') {
            const alertClass = `alert-${type}`;
            const iconClass = type === 'success' ? 'fa-check-circle' : 
                             type === 'danger' ? 'fa-exclamation-circle' : 
                             type === 'warning' ? 'fa-exclamation-triangle' : 'fa-info-circle';
            
            const messageHtml = `
                <div class="alert ${alertClass}">
                    <i class="fas ${iconClass}"></i> ${message}
                </div>
            `;
            
            messageArea.innerHTML = messageHtml;
            
            // 3秒后自动隐藏消息
            setTimeout(() => {
                messageArea.innerHTML = '';
            }, 3000);
        }

        // 进度条模态框函数
        function showProgressModal(title = '正在处理...', status = '请稍候...') {
            const modal = document.getElementById('progressModal');
            const titleElement = document.getElementById('progressTitle');
            const statusElement = document.getElementById('progressStatus');
            const progressBar = document.getElementById('progressBarModal');
            
            titleElement.textContent = title;
            statusElement.textContent = status;
            progressBar.style.width = '0%';
            progressBar.textContent = '0%';
            
            modal.style.display = 'flex';
        }

        function hideProgressModal() {
            const modal = document.getElementById('progressModal');
            modal.style.display = 'none';
        }

        function updateProgressModal(percent, status = '') {
            const progressBar = document.getElementById('progressBarModal');
            const statusElement = document.getElementById('progressStatus');
            
            progressBar.style.width = percent + '%';
            progressBar.textContent = percent + '%';
            
            if (status) {
                statusElement.textContent = status;
            }
        }

        // 本地存储功能
        function saveHistoryData() {
            localStorage.setItem('fileCognizeHistory', JSON.stringify(historyData));
        }

        function loadHistoryData() {
            const saved = localStorage.getItem('fileCognizeHistory');
            if (saved) {
                historyData = JSON.parse(saved);
                if (historyData.length > 0) {
                    historySection.style.display = 'block';
                    renderHistoryTable();
                }
            }
            
            // 同时从服务器加载历史记录
            loadHistoryFromServer();
        }

        // 服务器端历史记录管理
        async function saveHistoryToServer(historyItem) {
            try {
                const response = await fetch('/api/save-history', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(historyItem)
                });

                if (response.ok) {
                    console.log(`✅ 历史记录已保存到服务器: ${historyItem.id}`);
                    return true;
                } else {
                    const error = await response.json();
                    console.warn('服务器保存历史记录失败:', error.error);
                    return false;
                }
            } catch (error) {
                console.warn('服务器保存历史记录失败:', error);
                return false;
            }
        }

        async function loadHistoryFromServer() {
            try {
                const response = await fetch('/api/load-history');
                if (response.ok) {
                    const serverHistory = await response.json();
                    
                    // 合并服务器和本地历史记录，去重
                    const mergedHistory = mergeHistoryData(historyData, serverHistory);
                    
                    if (mergedHistory.length !== historyData.length) {
                        historyData = mergedHistory;
                        saveHistoryData(); // 更新本地存储
                        renderHistoryTable();
                        
                        if (historyData.length > 0) {
                            historySection.style.display = 'block';
                        }
                    }
                }
            } catch (error) {
                console.warn('从服务器加载历史记录失败:', error);
            }
        }

        // 合并历史记录数据，去重
        function mergeHistoryData(localHistory, serverHistory) {
            const merged = [...localHistory];
            const existingIds = new Set(localHistory.map(item => item.id));
            
            // 添加服务器端不存在于本地的记录
            serverHistory.forEach(serverItem => {
                if (!existingIds.has(serverItem.id)) {
                    merged.push(serverItem);
                }
            });
            
            // 按时间倒序排列
            return merged.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
        }

        // 删除记录时同时删除服务器端记录
        async function deleteHistoryFromServer(recordId) {
            try {
                await fetch(`/api/delete-history/${recordId}`, {
                    method: 'DELETE'
                });
            } catch (error) {
                console.warn('服务器删除历史记录失败:', error);
            }
        }
    </script>

    <!-- 进度条模态框 -->
    <div id="progressModal" class="progress-modal">
        <div class="progress-modal-content">
            <div class="spinner"></div>
            <h3 id="progressTitle">正在处理...</h3>
            <div class="progress">
                <div id="progressBarModal" class="progress-bar" style="width: 0%">0%</div>
            </div>
            <div id="progressStatus" class="progress-status">请稍候...</div>
        </div>
    </div>
</body>
</html> 